<script setup>
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import axios from "axios";
import {userStore} from "@/store/index.js";

// 定义表单数据
const form = ref({
  username: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  realName: '',
  phone: '',
  email: '',
  code: ''
});



// 表单引用
const formRef = ref(null);

// 验证确认密码的函数
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== form.value.password) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

// 自定义邮箱格式校验函数
const validateEmail = (rule, value, callback) => {
  const emailRegex = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱地址'));
  } else {
    callback();
  }
};

// 定义验证规则
const rules = {
  username: [{ required: true, message: '请输入账号名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { validator: validateEmail, trigger: 'blur' }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
};


//倒计时

// 发送验证码的函数
//发送验证码按钮控制
const btnTime2 = ref(false);
//按钮文本
const btnText2 = ref("发送验证码");
//获取邮箱验证码
const sendEmailCode = () =>{
  formRef.value.validateField('email',(valid) => {
    if (valid) {
      axios.get(`/user/getEmailCode/${form.value.email}`).then(resp => {
        ElMessage.success(resp.data);
      }).catch(error => {
        ElMessage.error(error.response.data)
      }).finally(() => {
        btnTime2.value = true;

        let seconds = 15;

        const timers = setInterval( () => {
          seconds--;
          if(seconds > 0){
            btnText2.value = `${seconds}后重新发送`;
          }else{
            btnTime2.value = false;
            btnText2.value = "发送验证码"
            clearInterval(timers);
          }
        },1000)
      })
    } else {
      ElMessage.warning('请输入正确格式的邮箱')
    }
  })
}


// 提交表单的函数
const store = userStore();
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 提交表单逻辑
      axios.post("/user/createNewAccount", form.value).then(resp => {
        store.updateUser(resp.data);
        store.updateLoginStatus(true);
        ElMessage.success("注册成功");
        // router.push("/getBookByType?id=0")
      }).catch(error => {
      })
    } else {
      ElMessage.error('请检查表单信息');
      return false;
    }
  });
};
</script>

<template>
  <div class="register-form">
    <h2>大健康：用户注册</h2>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <!-- 用户名 -->
      <el-form-item label="账号名" prop="account">
        <el-input v-model="form.username" placeholder="请输入用户账号"></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password" placeholder="请输入用户密码"></el-input>
      </el-form-item>
      <!-- 确认密码 -->
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input type="password" v-model="form.confirmPassword" placeholder="请输入确认密码"></el-input>
      </el-form-item>
      <!-- 昵称 -->
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="form.nickname" placeholder="请输入用户昵称"></el-input>
      </el-form-item>
      <!-- 真实姓名 -->
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="form.realName" placeholder="请输入真实姓名"></el-input>
      </el-form-item>
      <!-- 手机号 -->
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入正确的手机号"></el-input>
      </el-form-item>
      <!-- 邮箱地址 -->
      <el-form-item label="邮箱地址" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱地址"></el-input>
        <el-button type="primary" :disabled="btnTime2" @click="sendEmailCode">{{btnText2}}</el-button>
      </el-form-item>
      <!-- 验证码 -->
      <el-form-item label="验证码" prop="verificationCode">
        <el-input v-model="form.code" placeholder="请输入验证码"></el-input>
      </el-form-item>
      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="success" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.register-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ebebeb;
  border-radius: 5px;
}
</style>